const app = getApp()
import {
  reqConsumerDeviceList,
  reqConsumerRoomList,
} from '../../../../request/api.js'
import {
  showMsg
} from '../../../../utils/config.js'

Component({
  properties: {},
  options: {
    addGlobalClass: true
  },
  data: {
    navMarginTop: app.globalData.navMarginTop + 'px', //导航栏高度
    navBarHeight: app.globalData.navBarHeight + 'px', //头部标题高度
    navHeight: app.globalData.navHeight + 'px', //头部距离
    bottomHeight: app.globalData.bottomHeight + 'px', //iphone底部距离

    deviceImg: '/statics/images/gaojing/yangan.png',

    showFamilyPopup: false, //家庭选择弹出
    familyInfo: "",

    scrollIntoRoom: '',
    roomActive: 0,

    roomList: [],
    dataList: null,
    triggered: false, //是否下拉刷新列表

    isUpdataList: false, //是否更新列表:在其他页面对设备做出修改之后
    isRoomManagementVisible: false, // 控制 roomManagement 显示或隐藏
    x: '580rpx',
    y: '1080rpx',
  },
  lifetimes: {
    // 组件挂载到页面时触发
    attached() {
      this.setNavigationBarColorFun()
    },
    onReady() {
      // 预获取位置（可选）
      // this.getButtonPosition()
    },

  },

  pageLifetimes: {
    async show() {
      this.setData({
        familyInfo: app.globalData.familyInfo
      })
      console.log(app.globalData.isUpdateCIndex,'222');
      if (this.data.isUpdataList || app.globalData.isUpdateCIndex) {
        this.getConsumerRoomList()
        this.setData({
          isUpdataList: false
        })
        app.globalData.isUpdateCIndex = false
        wx.setStorageSync('isUpdateCIndex', false);
      }
    },
  },

  methods: {
    setNavigationBarColorFun() {
      wx.setNavigationBarColor({
        frontColor: '#000000', // 前景颜色，包括标题和按钮
        backgroundColor: '#000000', // 背景颜色
        animation: { // 动画效果（可选）
          duration: 400, // 动画持续时间，单位毫秒
          timingFunc: 'easeIn' // 动画效果
        }
      })
    },

    onFamily() {
      this.setData({
        showFamilyPopup: true
      })
    },
    familyHandle(e) {
      this.setData({
        showFamilyPopup: false,
      })
      console.log(e,'eee');
      if (e.detail.action == 'confirm') {
        if (e.detail.familyInfo.id) {
          // if (e.detail.familyInfo.id === this.data.familyInfo.id) return//lc
          if (e.detail.familyInfo.id ===( this.data.familyInfo && this.data.familyInfo.id)) return
          this.setData({
            familyInfo: e.detail.familyInfo,
            scrollIntoRoom: '',
            roomActive: 0,
          })
          this.getConsumerRoomList() //房间列表
        } else {
          // 场景：删除最后一个家庭时
          this.setData({
            familyInfo: {},
            scrollIntoRoom: '',
            roomActive: 0,
            roomList: [],
            dataList: [],
          })
        }
      }
    },

    //房间列表
    async getConsumerRoomList() {
      console.log('房间列表');
      let params = {
        homeId: this.data.familyInfo.id,
      }
      const res = await reqConsumerRoomList(params)
      if (res.code !== 20000) return showMsg(res.message)
      let {
        rows
      } = res.data
      // rows.unshift({
      //   id: 0,
      //   roomName: '所有设备',
      // })
      this.setData({
        roomList: rows || []
      })
      // console.log(rows);
      this.getDataList() //设备列表
    },
    //设备列表
    async getDataList() {
      const res = await reqConsumerDeviceList({
        homeId: this.data.familyInfo.id,
      })
      if (res.code != 20000) return showMsg(res.message)
      let {
        rows
      } = res.data
      // console.log(rows);

      // 用于存储分组后的数据
      const dataList = [];
      // 用于存储按 roomId 分组的数据
      const roomGroups = {};
      // 用于存储所有设备的列表
      let allDevicesList = [];
      // 初始化 roomGroups 和 dataList
      this.data.roomList.forEach(room => {
        roomGroups[room.id] = {
          roomId: room.id,
          roomName: room.roomName,
          homeId: room.homeId,
          list: []
        };
        dataList.push(roomGroups[room.id]);
      });
      // 遍历设备列表并分组
      rows.forEach(item => {
        // 将设备添加到所有设备列表
        allDevicesList.push({
          roomName: item.roomName,
          deviceName: item.deviceName,
          id: item.id,
          deviceCode: item.deviceCode,
          roomId: item.roomId,
          pic: item.pic,
          deviceType: item.deviceType,
          productModel: item.productModel,
          isAlarm:item.isAlarm,
        });
        // 将设备添加到相应的房间分组
        if (roomGroups[item.roomId]) {
          roomGroups[item.roomId].list.push({
            ...item
          });
        }
      });
      // 添加所有设备分组
      dataList.unshift({
        roomId: 0,
        roomName: '所有设备',
        list: allDevicesList
      });
      console.log(dataList, 'dataList');

      this.setData({
        dataList: dataList || []
      })
    },

    async onRefresh() {
      this.setData({
        triggered: true,
      })
      await this.getConsumerRoomList()
      this.setData({
        triggered: false,
      })
    },

    onRoom(e) {
      // console.log(e);
      const info = e.currentTarget.dataset.item
      console.log(e.currentTarget.dataset.index);
      this.setData({
        scrollIntoRoom: `room${e.currentTarget.dataset.index}`,
        roomActive: e.currentTarget.dataset.index
      })
    },
    onSwiperChange(e) {
      const {
        current
      } = e.detail
      // console.log(current, 'current');
      this.setData({
        scrollIntoRoom: `room${current}`,
        roomActive: current
      })
    },

    enitRoom(e){
      const {
        item
      } = e.currentTarget.dataset
      console.log(item);
      wx.navigateTo({
        url: '/packageC/pages/room/detail/detail',
        events: {
          receiveDataFromDetail: function (res) {
            if (res.isUpdataList) {
              // _this.getDataList()
            }
          },
        },
        success: function (res) {
          res.eventChannel.emit('sendDataToDetail', {
            data: item
          })
        }
      })
    },
    onAddDevice() {
      wx.navigateTo({
        url: '/packageC/pages/device/add/add',
      })
    },

    onDetail(e) {
      let item = JSON.stringify(e.currentTarget.dataset.item)
      console.log(e.currentTarget.dataset.item);
      // wx.navigateTo({
      //   url: `/packageC/pages/device/detail/detail?item=${item}`,
      // })
      // return;
      if(e.currentTarget.dataset.item.deviceType=='DoorMagnetism'){
        wx.navigateTo({
          url: `/packageC/pages/device/detailDoorMagnetism/detailDoorMagnetism?item=${item}`,
        })
      }else{
        wx.navigateTo({
          url: `/packageC/pages/device/detail/detail?item=${item}`,
        })
      }
    },

    onDeviceLongPress(e) {
      const item = e.currentTarget.dataset.item
      const _this = this
      let {
        dataList,
        roomActive
      } = this.data
      console.log(item);
      wx.vibrateLong()
      wx.navigateTo({
        url: '/packageC/pages/device/device/device',
        events: {
          receiveDataFromDevice: function (res) {
            if (res.isUpdataList) {
              _this.setData({
                isUpdataList: true
              })
            }
          },
        },
        success: function (res) {
          res.eventChannel.emit('sendDataToDevice', {
            data: dataList[roomActive].list
          })
        }
      });
    },

    onAddFamily() {
      wx.navigateTo({
        url: '/packageC/pages/family/add/add',
      })
    },
    clearLongPress() {
      // 兼容iOS特殊处理
      wx.createSelectorQuery()
        .selectAll('.item')
        .boundingClientRect()
        .exec(() => {})
    },
    // 切换显示状态
    toggleRoomManagement() {
      this.setData({
        isRoomManagementVisible: !this.data.isRoomManagementVisible,
      });
    },
    // 隐藏 roomManagement
    hideRoomManagement() {
      this.setData({
        isRoomManagementVisible: false,
      });
    },
    // 空函数，用于阻止事件冒泡
    noop() {},
    roomAdd() {
      this.setData({
        isRoomManagementVisible: false
      })
      app.globalData.isUpdateCIndex = true
      wx.setStorageSync('isUpdateCIndex', true);
      wx.navigateTo({
        url: '/packageC/pages/room/room/room',
        events: {
          receiveDataFromRoom: function (res) {
            // _this.setData({
            //   "form.roomCount": res.data
            // });
            // _this.notifyPageUpdataFoo()
          },
        },
        success: function (res) {
          res.eventChannel.emit('sendDataToRoom', {
            data: app.globalData.familyInfo
          })
        }
      })
    },
    deviceAdd() {
      const _this = this
      let {
        dataList,
        roomActive
      } = this.data
      this.setData({
        isRoomManagementVisible: false
      })
      wx.navigateTo({
        url: '/packageC/pages/device/device/device',
        events: {
          receiveDataFromDevice: function (res) {
            if (res.isUpdataList) {
              _this.setData({
                isUpdataList: true
              })
            }
          },
        },
        success: function (res) {
          res.eventChannel.emit('sendDataToDevice', {
            data: dataList[0].list
          })
        }
      });
    },
    // getordinary(){
    //   // 通过选择器获取子组件实例
    //   const child = this.selectComponent('#family-popup');
    //   if (child) {
    //     child.getDataList(true); // 调用子组件方法
    //   }
    // },
  }
})